#include "testrapidjson.h"

#include <rapidjson/document.h>
#include <rapidjson/pointer.h>
#include <rapidjson/prettywriter.h>
#include <rapidjson/schema.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>

#include <QFile>
#include <QtTest>
#include <iostream>

/**
 * @brief 读取一个文本文件的内容
 * 
 * @param filePath 文件路径
 * @return QString 文件内容. 如果文件不存在则返回空字符串
 */
static QString readFileContentAsQString(const QString& filePath) {
    QFile file(filePath);
    if (!file.exists()) {
        return {};
    }
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return {};
    }
    return file.readAll();
}

/**
 * @brief 输出 json
 * 
 * @param doc rapidjson::Document 实例
 * @param pretty 是否格式化输出
 */
static void printJson(rapidjson::Document& doc, bool pretty = false) {
    rapidjson::StringBuffer buffer;
    if (pretty) {
        rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
        doc.Accept(writer);
    } else {
        rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
        doc.Accept(writer);
    }

    std::cout << "json content:" << buffer.GetString() << std::endl;
}

bool TestRapidJson::testReadJson() {  // NOLINT
    auto jsonQString = readFileContentAsQString("plugins.json");
    if (jsonQString.isEmpty()) {
        return false;
    }

    rapidjson::Document doc;
    doc.Parse(jsonQString.toStdString().c_str());
    if (doc.HasParseError()) {
        return false;
    }
    printJson(doc, true);
    return true;
}

void TestRapidJson::testRapidJsonAll() {
    // QVERIFY(testReadJson());
    // SPDLOG_LOGGER_INFO(log, fmt::format("\n\n"));
    // QVERIFY(testSchemaValidate());
    // SPDLOG_LOGGER_INFO(log, fmt::format("\n\n"));
    QVERIFY(testReadJson());
}